package com.qiantu.phone.ui.activity;

import static com.qiantu.api.entity.RoomBean.ROOM_COMMON_SERIALNO;

import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.http.listener.HttpCallback;
import com.lxj.xpopup.XPopup;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLFloorDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.entity.SceneDetailBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.event.RefreshFloorRoomEvent;
import com.qiantu.phone.ui.adapter.ManagerDeviceAdapter;
import com.qiantu.phone.ui.dialog.BottomDeviceFilterDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;

public class RoomDeviceAddActivity  extends AppActivity {
    private android.widget.TextView selectArea;
    private View btnFilter;
    private View btnChoose;
    private EditText mEditSearch;
    private androidx.recyclerview.widget.RecyclerView deviceList;
    private ManagerDeviceAdapter mManagerDeviceAdapter;
    private BottomDeviceFilterDialog mBottomDeviceFilterDialog;
    private List<DeviceBean> allDevices;
    private Boolean isAllSelect = false;
    Map<String,Integer> taskData = new HashMap<>();
    private  int type;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_device_action;
    }

    @Override
    protected void initView() {
        type = getInt("type");

        getTitleBar().setRightTitle(R.string.save);
        mEditSearch = findViewById(R.id.edit_search);
        selectArea = findViewById(R.id.select_area);
        btnFilter = findViewById(R.id.btn_filter);
        btnChoose = findViewById(R.id.btn_all_choose);
        deviceList = findViewById(R.id.device_list);
        setOnClickListener(R.id.btn_filter,R.id.btn_all_choose);
        mEditSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length() > 0){
                    searchDevice(s.toString());
                }else{
                    if(mBottomDeviceFilterDialog == null){
                        getLocalDevices();
                    }else{
                        loadSelectedDevices();
                    }
                }
            }
        });
        if(type == 1){
            getTitleBar().setTitle("添加常用设备");
            btnFilter.setVisibility(View.VISIBLE);
        }else{
            getTitleBar().setTitle(R.string.add_device);
            btnFilter.setVisibility(View.GONE);
        }
    }

    private void loadSelectedDevices(){
        showDialog();
        Observable.create(new ObservableOnSubscribe<List<DeviceBean>>() {
                    @Override
                    public void subscribe(ObservableEmitter<List<DeviceBean>> emitter) throws Exception {
                        List<DeviceBean> devices = mBottomDeviceFilterDialog.getAllDeviceFormSelectArea();
                        emitter.onNext(devices);
                    }
                }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<DeviceBean>>() {
                    @Override
                    public void accept(List<DeviceBean> devices) throws Exception {
                        mManagerDeviceAdapter.setTotalData(devices);
                        hideDialog();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                });
    }

    private void searchDevice(String keywords){
        if(allDevices != null){
            List<DeviceBean> searchDevices = new ArrayList<>();
            for(DeviceBean deviceBean : allDevices){
                if(deviceBean.getName() != null && deviceBean.getName().contains(keywords)){
                    searchDevices.add(deviceBean);
                }
            }
            mManagerDeviceAdapter.setTotalData(searchDevices);
        }
    }

    @Override
    protected void initData() {
        deviceList.setLayoutManager(new GridLayoutManager(getContext(), 2));
        mManagerDeviceAdapter = new ManagerDeviceAdapter(getContext(),taskData);
        deviceList.setAdapter(mManagerDeviceAdapter);
        mManagerDeviceAdapter.setSelectable(true);
        mManagerDeviceAdapter.setSingleSelect(false);
        mManagerDeviceAdapter.setShowOffline(true);
        getTitleBar().getRightView().setEnabled(true);
        getLocalDevices();
    }


    private void getLocalDevices(){
        showDialog();
        Observable.create(new ObservableOnSubscribe<List<DeviceBean>>() {
                    @Override
                    public void subscribe(ObservableEmitter<List<DeviceBean>> emitter) throws Exception {
                        List<DeviceBean> devices;
                        if(type == 2){
                            devices = LLDeviceDBManager.getInstance(getContext()).getCommonDevices();
                        }else{
                            devices = LLDeviceDBManager.getInstance(getContext()).getAll(false,null,null);
                        }

                        emitter.onNext(devices);
                    }
                }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<DeviceBean>>() {
                    @Override
                    public void accept(List<DeviceBean> devices) throws Exception {
                        hideDialog();
                        allDevices = devices;
                        mManagerDeviceAdapter.setTotalData(devices);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                });
    }

    @Override
    public void onRightClick(View view) {
        Map data = new HashMap<>();
        String roomSerialNo = getString("roomSerialNo");
        //1房间绑定 2房屋绑定(移除房间,绑定到房屋)
        data.put("type", 1);
        data.put("targetSerialNo", roomSerialNo);

        List<DeviceBean> selectedDevices = mManagerDeviceAdapter.getSelectedData();
        List<String> selectedSerialNos = new ArrayList<>();
        List<String> selecteGroupdSerialNos = new ArrayList<>();
        for (DeviceBean deviceBean : selectedDevices) {
            if (deviceBean.getDeviceGroup() == 0) {
                selectedSerialNos.add(deviceBean.getDeviceSerialNo());
            } else {
                selecteGroupdSerialNos.add(deviceBean.getDeviceSerialNo());
            }
        }
        if (type == 1) {
            LLHttpManager.favouritedevice(this, selectedSerialNos, selecteGroupdSerialNos,
                    new HttpCallback<HttpData<Void>>(this) {
                        @Override
                        public void onStart(Call call) {
                            showDialog(null);
                        }

                        @Override
                        public void onSucceed(HttpData<Void> result) {
                            for (DeviceBean device : selectedDevices) {
//                                    //设置RoomSerialNo之前保存,用来更新当前选中的房间下的场景
//                                    deviceRooms.add(device.getRoomSerialNo());
                                device.setIsFavourite(true);
                                LLDeviceDBManager.getInstance(getContext()).put(device);
                            }
                            toast(R.string.set_success);
                            EventBus.getDefault().post(new RefreshDeviceListEvent());
                            finish();
                        }

                        @Override
                        public void onFail(Exception e) {
                            super.onFail(e);
                        }
                    });
        } else {
            if (selectedSerialNos.size() != 0) {
                data.put("deviceSerialNoList", selectedSerialNos);
                LLHttpManager.deviceBelong(this, data,
                        new HttpCallback<HttpData<Void>>(this) {
                            @Override
                            public void onStart(Call call) {
                                showDialog(null);
                            }

                            @Override
                            public void onSucceed(HttpData<Void> result) {
                                if (selecteGroupdSerialNos.size() == 0) {
                                    finishChange(roomSerialNo);
                                } else {
                                    groupChange(roomSerialNo, selecteGroupdSerialNos);
                                }
                            }

                            @Override
                            public void onFail(Exception e) {
                                super.onFail(e);
                            }
                        });
            } else {
                groupChange(roomSerialNo, selecteGroupdSerialNos);
            }
        }
    }

    public void groupChange(String roomSerialNo,List<String> selecteGroupdSerialNos) {
        Map data = new HashMap<>();
        //1房间绑定 2房屋绑定(移除房间,绑定到房屋)
        data.put("type", 1);
        data.put("targetSerialNo", roomSerialNo);

            data.put("deviceGroupSerialNos", selecteGroupdSerialNos);

            LLHttpManager.deviceGroupBelong(this, data,
                    new HttpCallback<HttpData<Void>>(this) {
                        @Override
                        public void onStart(Call call) {
                            showDialog(null);
                        }

                        @Override
                        public void onSucceed(HttpData<Void> result) {
                            finishChange(roomSerialNo);
                        }

                        @Override
                        public void onFail(Exception e) {
                            super.onFail(e);
                        }
                    });
    }

    private void finishChange(String roomSerialNo){
        RoomBean roomBean = LLRoomDBManager.getInstance(getContext()).getRoomByRoomSerialNo(roomSerialNo);
        List<DeviceBean> selectedDevices = mManagerDeviceAdapter.getSelectedData();
        if (selectedDevices != null && selectedDevices.size() > 0) {
//                                List<String> deviceRooms = new ArrayList<>();
            for (DeviceBean device : selectedDevices) {
//                                    //设置RoomSerialNo之前保存,用来更新当前选中的房间下的场景
//                                    deviceRooms.add(device.getRoomSerialNo());
                device.setRoomSerialNo(roomSerialNo);
                device.setLinkType(1);
                device.setRoomName(roomBean.getRoomName());
                FloorBean floor = LLFloorDBManager.getInstance(getContext()).getFloorByFloorSerialNo(roomBean.getFloorSerialNo());
                if (floor != null) {
                    device.setFloorName(floor.getFloorName());
                    device.setFloorSerialNo(floor.getFloorSerialNo());
                }
                LLDeviceDBManager.getInstance(getContext()).put(device);
            }
            toast(R.string.set_success);
            EventBus.getDefault().post(new RefreshDeviceListEvent());
            EventBus.getDefault().post(new RefreshFloorRoomEvent());
        }
        finish();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_filter:
                showBottomDeviceFilterDialog();
                break;
            case R.id.btn_all_choose:
                touchAllSelectButton();
                break;
        }
    }

    public void touchAllSelectButton(){
        isAllSelect = !isAllSelect;
        mManagerDeviceAdapter.setAllSelect(isAllSelect);
        btnChoose.setSelected(isAllSelect);
    }

    private void showBottomDeviceFilterDialog() {
        if (mBottomDeviceFilterDialog == null) {
            mBottomDeviceFilterDialog = new BottomDeviceFilterDialog(getContext(), BottomDeviceFilterDialog.TYPE_DEVICE, BottomDeviceFilterDialog.AVAILABLE_DEVICE) {
                @Override
                public void onConfirm(boolean hasFilter, List<DeviceBean> result) {
                    btnFilter.setSelected(hasFilter);
                    mManagerDeviceAdapter.setTotalData(result);
                }
            };
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .enableDrag(false)
                    .asCustom(mBottomDeviceFilterDialog);
        }
        mBottomDeviceFilterDialog.setInitCount(mManagerDeviceAdapter.getItemCount());
        List<FloorBean> floors = LLFloorDBManager.getInstance(getContext()).getNotEmptyRoomFloors();
        mBottomDeviceFilterDialog.setFloorBeans(floors);
        mBottomDeviceFilterDialog.show();
    }

}
